package iyzhan.cp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;


public class Ma extends Activity {
	private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_ma);
        tv=(TextView) findViewById(R.id.t1);
        handleIntent(getIntent());
    }


    private void handleIntent(Intent intent) {
    	tv.setText("Copy file to Download.");
    	Uri data=intent.getData();
    	if(data!=null)cp(data);
    }
    private void cp(Uri u){
    	File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    	String fn=u.getPath();
    	tv.setText(fn);
    	File sf=new File(fn);
		File df=new File(dir,sf.getName());
		if(df.exists()){
			String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
			df=new File(dir,timestamp+sf.getName());
		}
    	
    	try{
    		ContentResolver contentResolver = getContentResolver();
    	    InputStream in = contentResolver.openInputStream(u);
    	    FileOutputStream out = new FileOutputStream(df);
    	    ReadableByteChannel rbc=Channels.newChannel(in);
    	    FileChannel fc=out.getChannel();
    	    long size=fc.transferFrom(rbc, 0, Long.MAX_VALUE);
            in.close();
            out.close();
            tv.setText(fn+" copied.\nTarget:"+df.getPath()+"\nSize: "+size+"byte(s)");
    	}catch(Exception e){
    		tv.setText(e.getMessage());
    	}
    	
    }
    @Override
    public void onBackPressed(){
    	finish();
    }
    
}

